package com.itts.middle.config.interceptor;

import com.alibaba.fastjson.JSON;
import com.itts.common.annotations.Open;
import com.itts.common.enums.ErrorEnum;
import com.itts.common.util.result.R;

import com.itts.middle.config.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Slf4j
public class TokenInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod h = (HandlerMethod) handler;
            Open methodAnnotation = h.getMethodAnnotation(Open.class);
            if (methodAnnotation == null) {
                return true;
            }
            Object token = request.getHeader("token");
            if (token == null) {
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                PrintWriter out = null;
                R r = R.error(ErrorEnum.TOKEN_ERROR);
                out = response.getWriter();
                out.append(JSON.toJSONString(r));
                return false;
            }

            try {
                JwtUtils.verifyToken((String) token);
                return true;
            } catch (Exception e) {
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                PrintWriter out = null;
                R r = R.error(ErrorEnum.TOKEN_EXPIRE);
                out = response.getWriter();
                out.append(JSON.toJSONString(r));
                return false;
            }
        }

        return true;
    }
}
